#!/usr/bin/env python3
# encoding=utf-8

import os, sys
import time
import logging.handlers
from commom_api import get_base_config
from get_email_by_imap import get_data_by_imap
from get_email_by_pop import get_data_by_pop
from code_process import get_codeinfo_from_emailinfo
from excel_process import fill_excel_with_code_value, filter_emailinfo_by_excel, remove_all_temp_file
import logging

def init_logging():
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.INFO)
    
    formatter = logging.Formatter("%(asctime)s - %(name)s-%(lineno)s - %(levelname)s - %(message)s")
    # 文件处理器（按天滚动，保留7天日志）
    file_handler = logging.handlers.TimedRotatingFileHandler(
        "mailapp.log",
        when="midnight",  # 每天午夜滚动
        interval=1,
        backupCount=7,
        encoding="utf-8"
    )
    # 文件Handler
    # file_handler = logging.FileHandler("mailapp.log", encoding='utf=8', mode='a')
    file_handler.setFormatter(formatter)
    root_logger.addHandler(file_handler)
    
    # 控制台Handler（可选）
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)
    root_logger.addHandler(console_handler)
    

if __name__=="__main__":
    # print(sys.argv)
    init_logging()   # 仅调用一次
    config = get_base_config()
    logger = logging.getLogger(__name__)
    sttime = time.time()
    logger.info(f"start to get email by {config['mailtype']}")
    # emailinfo = [{'name': '雷菱新势套利1号私募证券投资基金A', 'code': 'LY849A', 'date': '2025-03-28', 'value': '1.0061', 'totalvalue': '1.0634', 'benchmark': ['zs_399300']}]
    # emailinfo = [{'name': '雷菱10号私募证券投资基金A类', 'code': 'XJ723A', 'date': '2025-02-27', 'value': '1.0061', 'totalvalue': '1.0634', 'benchmark': ['zs_399300']}]
    # emailinfo += [{'name': '雷菱9号私募证券投资基金A类', 'code': 'LLSM9A', 'date': '2025-02-28', 'value': '1.0059', 'totalvalue': '1.0632', 'benchmark': ['zs_399300']}]
    # emailinfo = [{'name': '雷菱3号私募证券投资基金A', 'code': 'JN732B', 'date': '2025-02-28', 'value': '0.937', 'totalvalue': '1.239', 'benchmark': ['zs_000016', 'zs_399300', 'zs_399905', 'zs_399852']}]
    # emailinfo = [{'name': '雷菱吉量3号私募证券投资基金A', 'code': 'SVG907', 'date': '2025-02-28', 'value': '0.937', 'totalvalue': '1.239', 'benchmark': ['zs_000016', 'zs_399300', 'zs_399905', 'zs_399852']}]
    # emailinfo = [{'name': '雷菱吉量6号私募证券投资基金A', 'code': 'VJ124B', 'date': '2025-02-28', 'value': '1.1638', 'totalvalue': '1.4837', 'benchmark': ['zs_000016', 'zs_399300', 'zs_399905', 'zs_399852']}]
    if config['mailtype'] == "pop":
        emailinfo = get_data_by_pop()
    elif config['mailtype'] == "imap":
        emailinfo = get_data_by_imap()
    else:
        sys.exit(-1) 
    logger.info(f"emailinfo is {emailinfo}")


    # codeinfo = {'zs_000016': [['2025-02-14', 2660.85]], 'zs_399300': [['2025-02-14', 3939.01]], 'zs_399905': [['2025-02-14', 5947.8]], 'zs_399852': [['2025-02-14', 6248.83]]}   
    emailinfo = filter_emailinfo_by_excel(emailinfo)
    codeinfo = get_codeinfo_from_emailinfo(emailinfo)
    logger.info(f"codeinfo is {codeinfo}")

    remove_all_temp_file()
    fill_excel_with_code_value(emailinfo, codeinfo)
    endtime = time.time()
    logger.info(f"all task over use time {endtime-sttime}s")
